﻿using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Win32;

namespace ManilaToday
{
    class TabInstaller
    {
        const string ManilaTabsFile = @"\Windows\26948339_manila";
        const string BackupFile = ManilaTabsFile + ".bak";
        private static readonly Encoding _fileEncoding = Encoding.GetEncoding("utf-16");

        private static XmlDocument GetConfigManilaDocument()
        {
            XmlDocument xmlDocument = new XmlDocument();
            using (StreamReader sr = new StreamReader(ManilaTabsFile, _fileEncoding))
            {
                string xmlData = sr.ReadToEnd();
                xmlData = xmlData.Replace("&", "&amp;");
                xmlDocument.LoadXml(xmlData);
            }
            return xmlDocument;
        }

        private static void SaveConfigManilaDocument(XmlDocument document)
        {
            StringWriter sw = new StringWriter();
            document.Save(sw);

            FileInfo settingsFile = new FileInfo(ManilaTabsFile);
            if ((settingsFile.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                settingsFile.Attributes ^= FileAttributes.ReadOnly;
            }

            using (StreamWriter output = new StreamWriter(ManilaTabsFile, false, _fileEncoding))
            {
                output.Write(sw.GetStringBuilder().Replace("&amp;", "&").ToString());
            }
            settingsFile.Attributes |= FileAttributes.ReadOnly;
        }

        public static void InstallTodayTab()
        {
            if (!File.Exists(BackupFile))
            {
                File.Copy(ManilaTabsFile, BackupFile);
            }

            XmlDocument xmlDocument = GetConfigManilaDocument();
            XmlNode pagesRoot = xmlDocument.SelectSingleNode(@"/Manila/Navigation/PageGroup[@Name=""Root""]");

            XmlNode existingManilaPage = pagesRoot.SelectSingleNode(@"Page[@Name=""today.page""]");
            if (existingManilaPage == null)
            {
                int maxPageNumber = -1;
                foreach (XmlNode node in pagesRoot.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                        continue;

                    if (node.Name != "Page")
                        continue;

                    maxPageNumber = Math.Max(maxPageNumber,
                                             int.Parse(node.Attributes["Order"].Value, CultureInfo.InvariantCulture));
                }

                XmlNode manilaPageNode = xmlDocument.CreateNode(XmlNodeType.Element, "Page", string.Empty);

                XmlAttribute orderAttr = xmlDocument.CreateAttribute("Order");
                orderAttr.Value = (maxPageNumber + 1).ToString(CultureInfo.InvariantCulture);

                XmlAttribute packageNameAttr = xmlDocument.CreateAttribute("PackageName");
                packageNameAttr.Value = "HTC";

                XmlAttribute nameAttr = xmlDocument.CreateAttribute("Name");
                nameAttr.Value = "today.page";

                XmlAttribute titleAttr = xmlDocument.CreateAttribute("Title");
                titleAttr.Value = "Today Screen";

                manilaPageNode.Attributes.Append(orderAttr);
                manilaPageNode.Attributes.Append(packageNameAttr);
                manilaPageNode.Attributes.Append(titleAttr);
                manilaPageNode.Attributes.Append(nameAttr);
                manilaPageNode.InnerXml =
                    @"<ComponentReference Name=""page"" Mode9Path=""HTC\today.mode9"" Component=""GizmoRoot"" SmartComponent=""true""  />" +
                    @"<ComponentReference Name=""icon_normal""   Mode9Path=""HTC\todayicon.mode9"" Component=""today_Off"" />" +
                    @"<ComponentReference Name=""icon_selected"" Mode9Path=""HTC\todayicon.mode9"" Component=""today_On"" />" +
                    @"<ComponentReference Name=""icon_preview""  Mode9Path=""HTC\todayicon.mode9"" Component=""today_Preview"" />";

                pagesRoot.AppendChild(manilaPageNode);

                SaveConfigManilaDocument(xmlDocument);

               // AddTabToRegistry(maxPageNumber + 1);
            }
        }

        public static void UnInstalTodayTab()
        {
            XmlDocument xmlDocument = GetConfigManilaDocument();
            XmlNode pagesRoot = xmlDocument.SelectSingleNode(@"/Manila/Navigation/PageGroup[@Name=""Root""]");

            XmlNode existingManilaPage = pagesRoot.SelectSingleNode(@"Page[@Name=""today.page""]");
            if (existingManilaPage != null)
            {
                int todayTabOrder = int.Parse(existingManilaPage.Attributes["Order"].Value, CultureInfo.InvariantCulture);
                pagesRoot.RemoveChild(existingManilaPage);

                foreach (XmlNode node in pagesRoot.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                        continue;

                    if (node.Name != "Page")
                        continue;

                    int nodeOrder = int.Parse(node.Attributes["Order"].Value, CultureInfo.InvariantCulture);
                    if (nodeOrder > todayTabOrder)
                    {
                        node.Attributes["Order"].Value = (nodeOrder - 1).ToString(CultureInfo.InvariantCulture);
                    }
                }
                
                SaveConfigManilaDocument(xmlDocument);
            }
        }

        private static void AddTabToRegistry(int pageNumber)
        {
            using (var manilaConfKey = Registry.LocalMachine.CreateSubKey(
                    string.Format(CultureInfo.InvariantCulture, @"Software\HTC\Manila\Configuration\{0}", pageNumber)))
            {
                manilaConfKey.SetValue("Title", "[[Today Screen]]", RegistryValueKind.String);
                manilaConfKey.SetValue("PageName", "Manila://today.page", RegistryValueKind.String);
                manilaConfKey.SetValue("Enable", 1, RegistryValueKind.DWord);
            }
        }

        private static void RemoveTabFromRegistry(int pageNumber)
        {
            using (var manilaConfKey = Registry.LocalMachine.CreateSubKey(@"Software\HTC\Manila\Configuration"))
            {
                manilaConfKey.DeleteSubKeyTree(pageNumber.ToString(CultureInfo.InvariantCulture));

                string[] keys = manilaConfKey.GetSubKeyNames();
                foreach (var key in keys)
                {
                    try
                    {
                        int keyNumber = int.Parse(key, CultureInfo.InvariantCulture);
                       
                    }
                    catch (Exception)
                    {
                    }
                    
                }
            }

        }
    }
}
